package com.mht.student.service;



import com.mht.student.dao.StudentDao;
import com.mht.student.entity.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@SuppressWarnings("ALL")
public class StudentManageService implements StudentDao {
    private List<Student> students;


    public StudentManageService() {
        students = new ArrayList<>();
        loadStudentsFromFile("students.txt");
    }
    @Override
    public void addStudent(Student student) {
        students.add(student);
        saveStudentsToFile("students.txt");
        System.out.println("恭喜您，学生信息添加成功，并成功写入到文件！");
    }

    @Override
    public void deleteStudent(String studentId) {
        students.removeIf(student -> student.getId().equals(studentId));
        saveStudentsToFile("students.txt");
        System.out.println("恭喜您，学生信息删除成功，并成功从文件数据中移除需要删除的数据！");
    }

    @Override
    public void updateStudent(Student updatedStudent) {
        for (int i = 0; i < students.size(); i++) {
            if (students.get(i).getId().equals(updatedStudent.getId())) {
                students.set(i, updatedStudent);
                break;
            }
        }
        saveStudentsToFile("students.txt");
        System.out.println("恭喜您，学生信息修改成功，并成功更新到文件！");
    }

    @Override
    public Student getStudentById(String keyword) {
        return students.stream()
                .filter(student -> student.getId().contains(keyword) ).findFirst().orElse(null);
    }

    @Override
    public List<Student> getStudentList(String keyword) {
        if( keyword == null || keyword.trim().isEmpty()){
            return students;
        }else {
            return students.stream()
                    .filter(student -> student.getName().contains(keyword) || student.getId().contains(keyword) || student.getClassName().contains(keyword))
                    .collect(Collectors.toList());
        }
    }

    /**
     * 从文件中加载学生信息
      */
    private void loadStudentsFromFile(String filename) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filename))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(",");
                students.add(new Student(parts[0], parts[1], parts[2], Integer.parseInt(parts[3]), Integer.parseInt(parts[4]), Integer.parseInt(parts[5])));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Author wangfusheng
     * @date 2024-10-18 11:10:34
     * @description 保存学生信息到文件
     * @param fileName
     * @return void
     */
    private void saveStudentsToFile(String fileName) {
        try (PrintWriter writer = new PrintWriter(new FileWriter(fileName))) {
            for (Student student : students) {
                writer.println(student);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
